const ethUrl = 'https://kovan.infura.io/v3/4790cd7bb24349738a3b05ee0c20746e';
window.ethUrl = ethUrl
const CONTRACT_ADDRESS   = "0xDd13A1136Ec9bfC41458d3DB21d71b7D0Bf2eFc2";
window.CONTRACT_ADDRESS = CONTRACT_ADDRESS

const MATRIX_PRICE     = 0.05;
const DEFAULT_GASPRICE = 98e9;
const COOKIE_AUTH_NAME = 'auth';
window.COOKIE_AUTH_NAME = COOKIE_AUTH_NAME
let GASPRICE = config.gasPrice ? (config.gasPrice * 1e9) : DEFAULT_GASPRICE;

const debug = true

console.log('contract.js==>>GASPRICE', GASPRICE)


function requiredMetamask(){

}

window.l=(str)=>{
  return str
}

Notice = {
  error:(l)=>{
    console.log(`contract.js==>>Notice`, '#l', l)
  },
  warning:(l)=>{
    console.log(`contract.js==>>Notice`, '#l', l)
  },
  success:(l)=>{
    console.log(`contract.js==>>Notice`, '#l', l)
  },
}

window.getWeb3 = (callback, err) => {
  if(!window.ethereum && !window.web3) {
    Notice.error(
      l('notDetectedWallet')
    );
    return false;
  }

  if(!web3.eth.coinbase) {
    Notice.warning(
      l('unblockWallet')
    );
  }

  let i = 0;
  let id = setInterval(() => {
    if(i > 1800 || web3.eth.coinbase) {
      clearInterval(id);
      if(web3.eth.coinbase) {
        startApp();
        callback(window.web3, true);
      }
    } else if(++i == 1) {
      // Modern dapp browsers...
      if (window.ethereum) {
        if(ethereum.autoRefreshOnNetworkChange) {
          ethereum.autoRefreshOnNetworkChange = false;
        }
        window.web3 = new Web3(ethereum);
        try {
          // Request account access if needed
          ethereum.enable();
          startApp();
        } catch (error) {
          Notice.error(error.message);
          return false;
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        startApp();
      }
      else {
      }
    }
  }, 100);
};

config.site.MetaMaskNetId = '-1'

// Run app
function startApp() {
  //checking Main net
  web3.version && web3.version.getNetwork(function(err, netId){
    config.site.MetaMaskNetId = netId
    console.log('contract.js==>>startApp', '#config.site.MetaMaskNetId', config.site.MetaMaskNetId)
    if(netId !== "1"){
        //net ID must be 1; Show any message
    }
    switch (netId) {
      // This is mainnet
      case "1":
        break
      // This is the deprecated Morden test network
      case "2":
        break
      // This is the ropsten test network
      case "3":
        break
      // This is the Rinkeby test network
      case "4":
        break
      // This is the Kovan test network
      case "42":
        break
      // This is an unknown network
      default:
    }
  });

  try {
    DealContract = web3.eth.contract(contractAbi);
    DealContractInstance = DealContract.at(CONTRACT_ADDRESS);
  } catch (error) {
  }

  initData();
}

function initData() {
  // Если поддерживается библиотека web3
  document.body.classList.add('web3' in window ? 'web3' : 'noweb3');
}

setTimeout(function () {
  if(!window.ethereum) {
    return false;
  }
  // Обработка события при смене кошелька
  window.ethereum.on('accountsChanged', function (accounts) {
    console.log('contract.js==>>accountsChanged', '#accounts', accounts)
    window.changeEthWallet && window.changeEthWallet(accounts)
    if(config.user.isAuthSecure) {
      // Дезавторизация при смене кошелька
      if(config.user.address && config.user.address != web3.eth.coinbase) {
        setCookie(COOKIE_AUTH_NAME, '')
        window.location = '#/';
      }
    }
  });
  // Обработка события при смени сети
  window.ethereum.on('networkChanged', function (netId) {
    startApp()
    // window.location.reload()
  });
  startApp()
  getGasPrice()
}, 1000);

window.initGasPrice = false

function getGasPrice(callback) {
  if(window.initGasPrice){
    typeof callback === 'function' && callback()
  }else{
    if(window.web3 && window.web3.eth && window.web3.eth.getGasPrice){
      window.web3.eth.getGasPrice((err, res)=>{
        // window.initGasPrice = true
        GASPRICE = res.c[0]
        console.log('contract.js==>>getGasPrice', err, res)
        typeof callback === 'function' && callback(err, res)
      })
    }else{
      // window.initGasPrice = true
      typeof callback === 'function' && callback()
    }
  }
}

// Цифровая подпись кошелька
function signMessage(message){
  return new Promise(function(ok, fail){
    getWeb3(function(web3) {
      web3.personal.sign(web3.fromUtf8(message), web3.eth.coinbase, function(error, sign){
        if(error){
          fail(error)
        } else {
          ok(sign)
        }
      });
    });
  });
}

function getCurrentAddress(callback) {
  getWeb3(function(web3) {
    callback(web3.eth.coinbase);
  });
}


function getInfoByTransaction(tx, callback) {
  let defaultData = {
    block: null,
    blockNumber: 0,
    transaction: null,
    countConfirmation: 0
  };
  getWeb3(function(web3) {
    web3.eth.getBlockNumber(function (err, blockNumber) {
      if(err) {
        callback(err, defaultData);
        return false;
      }
      web3.eth.getTransaction(tx, function (err, transaction) {
        if(err) {
          callback(err, defaultData);
          return false;
        }
        if(!transaction) {
          callback(null, defaultData);
          return false;
        }
        web3.eth.getBlock(transaction.blockNumber, function (err, block) {
          if(err) {
            callback(err, defaultData);
            return false;
          }
          let countConfirmation = transaction.blockNumber === null ? 0 : blockNumber - transaction.blockNumber;
          callback(err, {
            block: block,
            blockNumber: blockNumber,
            transaction: transaction,
            countConfirmation: countConfirmation
          });
          return true;
        });
      });
    });
  });
}

/**
 *
 * @param {*} userAddress
 */
function getUsers(userAddress) {
  return new Promise((resolve, reject)=>{
    getWeb3((web3) => {
      if(web3 && DealContractInstance) {
        DealContractInstance.users(userAddress, function (err, result) {
          console.log(arguments)
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

function isMetaMaskUnlock(){
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      resolve(web3.eth.coinbase)
    })
  })
}

function unlockMetaMask(){
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      try {
        web3.enable()
      } catch (error) {
      }
      resolve()
    })
  })
}

function dw(methodName, _amount, _marketIdx) {
  console.log(`contract.js.vue==>>${methodName}, _amount: %o, _marketIdx: %o`, _amount, _marketIdx)
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      if(web3 && DealContractInstance) {
        DealContractInstance[methodName](_marketIdx, _amount, function (err, result) {
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

function deposit(_amount, _marketIdx = window._marketIdx){
  return dw('deposit', _amount, _marketIdx)
}

function withdraw(_amount, _marketIdx = window._marketIdx){
  return dw('withdraw', _amount, _marketIdx)
}

/**
 *
 * @param {*} _side 方向 0-多 1-空
 * @param {*} _size 开仓量，目标quote资产数量
 * @param {*} _price 开仓价，目标开仓价格，0-表示市场价，非0-表示委托价
 * @param {*} _leverage 杠杆倍数，1-10的整数
 * @param {*} _marketIdx
 * @returns
 */
function openPosition(_side, _size, _price, _leverage, _marketIdx = window._marketIdx) {
  console.log(`contract.js.vue==>>openPosition, arguments: %o`, arguments)
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      if(web3 && DealContractInstance) {
        // let size = parseFloat(_size)
        // let price = parseFloat(_price)
        DealContractInstance.openPosition(_marketIdx, _side, _size, _price, _leverage, function (err, result) {
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

/**
 *
 * @param {*} _side
 * @param {*} _size
 * @param {*} _price
 * @param {*} _marketIdx
 * @returns
 */
function closePosition(_side, _size, _price, _marketIdx = window._marketIdx){
  console.log(`contract.js.vue==>>closePosition, arguments: %o`, arguments)
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      if(web3 && DealContractInstance) {
        DealContractInstance.closePosition(_marketIdx, _side, _size, _price, function (err, result) {
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

/**
 * 取消开仓委托
 * @param {*} _side
 * @param {*} _index
 * @param {*} _marketIdx
 * @returns
 */
function cancelOpenPosition(_side , _index, _marketIdx = window._marketIdx){
  console.log(`contract.js.vue==>>closePosition, arguments: %o`, arguments)
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      if(web3 && DealContractInstance) {
        DealContractInstance.cancelOpenPosition(_marketIdx, _side, _index, function (err, result) {
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

/**
 * 取消平仓委托
 * @param {*} _side
 * @param {*} _index
 * @param {*} _marketIdx
 * @returns
 */
 function cancelClosePosition(_side , _index, _marketIdx = window._marketIdx){
  console.log(`contract.js.vue==>>closePosition, arguments: %o`, arguments)
  return new Promise((resolve, reject) => {
    getWeb3(web3=>{
      if(web3 && DealContractInstance) {
        DealContractInstance.cancelClosePosition(_marketIdx, _side, _index, function (err, result) {
          if(!err) {
            resolve(result)
          } else {
            reject(err)
          }
        })
      }else{
        reject(new Error('No MetaMask'))
      }
    })
  })
}

const contractAbi = [
	{
		"inputs": [],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "market",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "enum ClearingHouse.Side",
				"name": "side",
				"type": "uint8"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "size",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "price",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "timestamp",
				"type": "uint256"
			}
		],
		"name": "Close",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "timestamp",
				"type": "uint256"
			}
		],
		"name": "Deposit",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "market",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "enum ClearingHouse.Side",
				"name": "side",
				"type": "uint8"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "size",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "price",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "leverage",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "timestamp",
				"type": "uint256"
			}
		],
		"name": "Open",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "previousOwner",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "OwnershipTransferred",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "timestamp",
				"type": "uint256"
			}
		],
		"name": "Withdraw",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_maintenanceMarginRatio",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_positionFeeRatio",
				"type": "uint256"
			}
		],
		"name": "addMarket",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "index",
				"type": "uint256"
			}
		],
		"name": "cancelClosePosition",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "index",
				"type": "uint256"
			}
		],
		"name": "cancelOpenPosition",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			}
		],
		"name": "checkClearing",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "checkLiquidate",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			}
		],
		"name": "clearing",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "_size",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_price",
				"type": "uint256"
			}
		],
		"name": "closePosition",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "deposit",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "fundBalance",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "getAccount",
		"outputs": [
			{
				"components": [
					{
						"internalType": "bool",
						"name": "isUsed",
						"type": "bool"
					},
					{
						"internalType": "uint256",
						"name": "accountBalance",
						"type": "uint256"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position",
						"name": "long",
						"type": "tuple"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position",
						"name": "short",
						"type": "tuple"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position[]",
						"name": "longOpenPending",
						"type": "tuple[]"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position[]",
						"name": "shortOpenPending",
						"type": "tuple[]"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position[]",
						"name": "longClosePending",
						"type": "tuple[]"
					},
					{
						"components": [
							{
								"internalType": "uint256",
								"name": "size",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openPrice",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "openNotional",
								"type": "uint256"
							},
							{
								"internalType": "uint256",
								"name": "leverage",
								"type": "uint256"
							}
						],
						"internalType": "struct ClearingHouse.Position[]",
						"name": "shortClosePending",
						"type": "tuple[]"
					}
				],
				"internalType": "struct ClearingHouse.Account",
				"name": "",
				"type": "tuple"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getLatestPrice",
		"outputs": [
			{
				"internalType": "int256",
				"name": "",
				"type": "int256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			}
		],
		"name": "getMarketSize",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			}
		],
		"name": "getMarketUnrealizedPnl",
		"outputs": [
			{
				"internalType": "int256",
				"name": "",
				"type": "int256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "_price",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_leverage",
				"type": "uint256"
			}
		],
		"name": "getMaxOpenSize",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "index",
				"type": "uint256"
			}
		],
		"name": "getPendingClosePosition",
		"outputs": [
			{
				"components": [
					{
						"internalType": "uint256",
						"name": "size",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openPrice",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openNotional",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "leverage",
						"type": "uint256"
					}
				],
				"internalType": "struct ClearingHouse.Position",
				"name": "",
				"type": "tuple"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "getPendingMargin",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "index",
				"type": "uint256"
			}
		],
		"name": "getPendingOpenPosition",
		"outputs": [
			{
				"components": [
					{
						"internalType": "uint256",
						"name": "size",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openPrice",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openNotional",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "leverage",
						"type": "uint256"
					}
				],
				"internalType": "struct ClearingHouse.Position",
				"name": "",
				"type": "tuple"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			}
		],
		"name": "getPosition",
		"outputs": [
			{
				"components": [
					{
						"internalType": "uint256",
						"name": "size",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openPrice",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "openNotional",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "leverage",
						"type": "uint256"
					}
				],
				"internalType": "struct ClearingHouse.Position",
				"name": "",
				"type": "tuple"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "getPositionMargin",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			}
		],
		"name": "getSpotPrice",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "getTotalMargin",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "getUnrealizedPnl",
		"outputs": [
			{
				"internalType": "int256",
				"name": "",
				"type": "int256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "_trader",
				"type": "address"
			}
		],
		"name": "liquidatePosition",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"name": "markets",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "maintenanceMarginRatio",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "positionFeeRatio",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "marketBalance",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "spotPrice",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "enum ClearingHouse.Side",
				"name": "_side",
				"type": "uint8"
			},
			{
				"internalType": "uint256",
				"name": "_size",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_price",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_leverage",
				"type": "uint256"
			}
		],
		"name": "openPosition",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "renounceOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "_price",
				"type": "uint256"
			}
		],
		"name": "setSpotPrice",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "transferOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_marketIdx",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "withdraw",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	}
]
window.contractAbi = contractAbi


